import React, { useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
import { Modal } from 'antd';

import cls from 'classnames';
import BuildTitle from '@/components/BuildTitle';
import './index.less';
import { ModalEngine } from './ModalEngine';
import { IModalProps, IOneModalRef } from './type';

const getKey = () => {
  return String(Math.random() * 1000000) + '-' + String(Math.random() * 1000000);
};

// const ModalClassName = 'class-' + parseInt(getKey());
// const ModalStyleId = 'modal-animation-style-' + parseInt(getKey());
// const ModalAnimateId = 'close-animate-' + parseInt(getKey());

let myObserver: any = null;
export const OneModal = React.forwardRef<IOneModalRef, IModalProps>(
  ({ title, className, children, formModalType, ...otherProps }, ref) => {
    // const ModalClassName = 'class-' + parseInt(getKey());

    const [ModalClassName, setModalClassName] = useState<string>('class-' + parseInt(getKey()));
    const [ModalStyleId, setModalStyleId] = useState<string>('modal-animation-style-' + parseInt(getKey()));
    const [ModalAnimateId, setModalAnimateId] = useState<string>('close-animate-' + parseInt(getKey()));

    const ModalTitle = <BuildTitle title={title ?? ''} className={ModalClassName} />;

    const [modalHeight, setModalHeight] = useState<any>();

    useImperativeHandle(ref, () => ({
      onModalCancel: (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
        onCancel(e);
      },
    }));

    const oneModalRef = useRef<ModalEngine | null>(
      new ModalEngine({
        className: ModalClassName,
        styleId: ModalStyleId,
        animateId: ModalAnimateId,
      }),
    );

    const onCancel = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
      if (oneModalRef && oneModalRef.current) {
        if (otherProps?.onCancel) {
          oneModalRef.current?.closeModal(e, ModalClassName, otherProps.onCancel);
        }
      }
    };

    useEffect(() => {
      myObserver = new ResizeObserver((entries: any, observer: any) => {
        entries?.forEach((item: any) => {
          let bodyHeight: any = item?.contentRect?.height;
          if (bodyHeight != 0 && modalHeight != bodyHeight) {
            setModalHeight(bodyHeight);
          }
        });
      });

      //监听，可以多个
      if (document.getElementsByClassName(ModalClassName)[0]) {
        myObserver.observe(document.getElementsByClassName(ModalClassName)[0] as any);
      }

      return () => {
        /**
         * 取消监听
         */
        myObserver.unobserve(document.body);
      };
    }, []);

    useEffect(() => {
      if (oneModalRef && oneModalRef.current) {
        // if (typeof oneModalRef.current !== 'undefined') {
        //   oneModalRef.current?.mount();
        // }
      } else {
        oneModalRef.current = new ModalEngine({
          className: ModalClassName,
          styleId: ModalStyleId,
          animateId: ModalAnimateId,
        });
        oneModalRef.current?.mount();
      }

      return () => {
        oneModalRef.current?.unmount();
        oneModalRef.current = null;
      };
    }, []);

    useEffect(() => {
      if (oneModalRef && oneModalRef.current && modalHeight) {
        if (typeof oneModalRef.current !== 'undefined') {
          oneModalRef.current?.mount();
        }
      }
    }, [modalHeight]);

    /** 传入modal中的配置 */
    const modalConfig = useMemo(() => {
      let modalConfig = otherProps;
      delete modalConfig['formModalType'];
      return modalConfig;
    }, [otherProps]);

    return (
      <Modal
        title={ModalTitle}
        // getContainer={false}
        className={cls({
          [`${ModalClassName}`]: true,
          [`one-modal`]: true,
          [`${className}`]: className ? className : false,
        })}
        centered={true}
        transitionName=""
        open={true}
        okText={formModalType ? '暂存' : '确认'}
        cancelText={formModalType ? '关闭' : '取消'}
        {...modalConfig}
        onCancel={onCancel}
      >
        {children}
      </Modal>
    );
  },
);

OneModal.displayName = `One-modal-${getKey()}-${getKey()}`;
